# -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 09:48:22 2019

@author: JimmyMo
"""

import tensorflow as tf

from numpy.random import RandomState

tf.compat.v1.disable_eager_execution()

batch_size = 8 

w1 = tf.Variable(tf.random.normal([2, 3], stddev=1, seed=1)) 
w2 = tf.Variable(tf.random.normal([3, 1], stddev=1, seed=1)) 


x = tf.compat.v1.placeholder(tf.float32, shape=(None, 2), name='x-input')
y_ = tf.compat.v1.placeholder(tf.float32, shape=(None, 1), name='y-input')


a = tf.matmul(x, w1) 
y = tf.matmul(a, w2) 


cross_entropy = -tf.reduce_mean(input_tensor=y_ * tf.math.log(tf.clip_by_value(y, 1e-10, 1.0)))

train_step = tf.compat.v1.train.AdamOptimizer(0.001).minimize((cross_entropy)) 


rdm = RandomState(1) 
dataset_size = 128
X = rdm.rand(dataset_size, 2) 

Y = [[int(x1+x2 <1)] for (x1, x2) in X] 



with tf.compat.v1.Session() as sess:
    init_op = tf.compat.v1.global_variables_initializer() 
    sess.run(init_op) 
    print(sess.run(w1))
    print(sess.run(w2))

    '''
    w1 = [[-0.81131822, 1.48459876, 0.06532937], [-2.44270396, 0.0992484, 0.59122431]]
    w2 = [[-0.81131822, 1.48459876, 0.06532937]]
    '''

    STEPS = 10000
    for i in range(STEPS):
        start = (i * batch_size) % dataset_size  
        end = min(start + batch_size, dataset_size)  

        sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})
        if i % 1000 == 0:
            total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y})
            print("After %d training steps(s), cross entropy on all data is %g" % (i, total_cross_entropy))

    print(sess.run(w1))
    print(sess.run(w2))
    
# 使用GradientDescentOptimizer 经过50000次训练后cross entropy on all data is 0.0128177
# [[-1.1455467  1.9226303  0.1079087]
#  [-2.7937493  0.5711125  0.6349069]]
# [[-1.7749329 ]
#  [ 2.0031984 ]
#  [ 0.25528094]]
 
#  使用AdamOptimizer 经过10000次训练后cross entropy on all data is -0
#  [[-2.5939224  3.1860275  2.3882565]
#  [-4.11018    1.6826365  2.8342736]]
# [[-2.4300373]
#  [ 3.3341115]
#  [ 2.1006744]]